/*
 * Copyright (c) 2018, apexes.net. All rights reserved.
 *
 *         http://www.apexes.net
 *
 */
package net.apexes.vertx;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import io.vertx.core.Verticle;
import io.vertx.core.Vertx;
import io.vertx.core.impl.JavaVerticleFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @author <a href="mailto:hedyn@foxmail.com">HeDYn</a>
 */
public class GuiceVerticleFactory extends JavaVerticleFactory {

    private final String prefix;
    private final Module[] modules;
    private Injector injector;

    public GuiceVerticleFactory(String prefix, Module... modules) {
        this.prefix = prefix;
        this.modules = modules;
    }

    @Override
    public void init(Vertx vertx) {
        List<Module> list = new ArrayList<>();
        list.add(new VertxModule(vertx, new InjectorHolderImpl(this::getInjector)));
        for (Module module : modules) {
            list.add(module);
        }
        injector = Guice.createInjector(list.toArray(new Module[0]));
    }

    @Override
    public String prefix() {
        return prefix;
    }
    
    @Override
    public Verticle createVerticle(String verticleName, ClassLoader classLoader) throws Exception {
        Verticle verticle = super.createVerticle(verticleName, classLoader);
        if (verticle instanceof GuiceVerticle) {
            injector.injectMembers(verticle);
        }
        return verticle;
    }

    public Injector getInjector() {
        return injector;
    }
}
